import 'package:flutter/material.dart';
import 'package:news_app_api/helper/news.dart';
import 'package:news_app_api/helper/widgets.dart';
import 'package:news_app_api/models/article.dart';

class CategoryNews extends StatefulWidget {
  final String newsCategory;

  const CategoryNews({required this.newsCategory});

  @override
  _CategoryNewsState createState() => _CategoryNewsState();
}

class _CategoryNewsState extends State<CategoryNews> {
  List<Article> newslist = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    getNews();
  }

  void getNews() async {
    debugPrint('开始获取${widget.newsCategory}类别的新闻数据');
    try {
      NewsForCategorie news = NewsForCategorie();
      debugPrint('正在发起网络请求...');
      await news.getNewsForCategory(widget.newsCategory);
      debugPrint('网络请求完成，获取到${news.news.length}条新闻');
      
      if (mounted) {
        debugPrint('组件仍然挂载，准备更新状态');
        setState(() {
          newslist = news.news;
          _loading = false;
        });
        debugPrint('状态更新完成');
      } else {
        debugPrint('组件已卸载，取消状态更新');
      }
    } catch (e) {
      debugPrint('获取新闻数据时发生错误: ${e.toString()}');
      if (mounted) {
        setState(() {
          _loading = false;
        });
        debugPrint('错误处理完成，已更新加载状态');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Flutter",
              style: TextStyle(color: Colors.black87, fontWeight: FontWeight.w600),
            ),
            Text(
              "News",
              style: TextStyle(color: Colors.blue, fontWeight: FontWeight.w600),
            )
          ],
        ),
        actions: <Widget>[
          Opacity(
            opacity: 0,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: Icon(Icons.share),
            ),
          )
        ],
        backgroundColor: Colors.transparent,
        elevation: 0.0,
      ),
      body: _loading
          ? const Center(
              child: CircularProgressIndicator(),
            )
          : SingleChildScrollView(
              child: Container(
                margin: EdgeInsets.only(top: 16),
                child: ListView.builder(
                  itemCount: newslist.length,
                  shrinkWrap: true,
                  physics: ClampingScrollPhysics(),
                  itemBuilder: (context, index) {
                    return NewsTile(
                      imgUrl: newslist[index].urlToImage ?? "",
                      title: newslist[index].title ?? "",
                      desc: newslist[index].description ?? "",
                      content: newslist[index].content ?? "",
                      posturl: newslist[index].articleUrl ?? "",
                    );
                  },
                ),
              ),
            ),
    );
  }
}
